package com.ljyhhh.SmartCity.activity.fragment.login

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.alibaba.fastjson.JSONObject
import com.ljyhhh.SmartCity.R
import com.ljyhhh.SmartCity.activity.home.MineActivity
import com.ljyhhh.SmartCity.base.database.DBUtil
import com.ljyhhh.SmartCity.base.user.User
import com.ljyhhh.SmartCity.base.user.UserLogin
import kotlinx.android.synthetic.main.activity_login.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import okio.IOException
// xiao Tang a! ljyh
// want a girl friend!!!
// Maybe you could leave a hint
// I'll come for you
class FragmentLogin:Fragment() {
    var flag=0
    var login_flag=false
    lateinit var myContext: Context
    var users= mutableListOf<User>()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.activity_login,container,false)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.myContext=context
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        DBUtil.openDB(myContext)
        val sharedPref = myContext.getSharedPreferences("config", Context.MODE_PRIVATE)

        if (sharedPref != null) {
            check_auto_login.isChecked=sharedPref.getBoolean("auto_login",false)
        }
        login_button.setOnClickListener {
            val uname=input_uname.text.toString()
            val pwd=input_pwd.text.toString()

            if (uname.isNotEmpty() && pwd.isNotEmpty())
                context?.let { it1 ->
                    UserLogin().login(uname,pwd, it1)
                        .enqueue(object : Callback {
                            override fun onFailure(call: Call, e: IOException) {
//                                runOnUiThread {
//                                    Toast.makeText(context, "发生错误", Toast.LENGTH_SHORT)
//                                        .show()
//                                }
                            }

                            override fun onResponse(call: Call, response: Response) {
                                val res=response.body?.string()
//                                res?.let { it1 -> Log.d("res login", it1) }
                                val root= JSONObject.parseObject(res)
                                val code=root.getBooleanValue("success")
                                if(code){
                                    login_flag=true
                                    if(check_auto_login.isChecked){
                                        if (sharedPref != null) {
                                            with(sharedPref.edit()){
                                                putBoolean("auto_login",check_auto_login.isChecked)
                                                apply()
                                            }
                                        }
                                        val users = ContentValues().apply {
                                            put("username",uname)
                                            put("password",pwd)
                                        }
                                        DBUtil.add(users, context!!)
                                    }



            //                                TextDatePersistence(applicationContext).userTextWrite(User(username = uname, password = pwd),check_auto_login.isChecked)

            //                                with (sharedPref.edit()) {
            //
            //                                    putString("username", uname)
            //                                    putString("password",pwd)
            //                                    putBoolean("auto_login",check_auto_login.isChecked)
            //                                    apply()
            //                                }
//                                    runOnUiThread { Toast.makeText(context,"登录成功",Toast.LENGTH_SHORT).show() }


                                    startActivity(Intent(context, MineActivity::class.java))
                                }else{
//                                    runOnUiThread { Toast.makeText(context,"登录失败",Toast.LENGTH_SHORT).show() }
                                    input_pwd.text.clear()
                                    input_uname.text.clear()
                                }
                            }
                        })
                }
            else
                Toast.makeText(context,"请输入账号或密码",Toast.LENGTH_SHORT).show()
        }
        input_uname.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                users= context?.let { DBUtil.qurey(it,input_uname.text.toString()) }!!
                val unames= mutableListOf<String>()
                users.map { unames.add(it.username) }
                input_uname.setAdapter(ArrayAdapter(context!!,android.R.layout.test_list_item,unames))
//                users[0].let { Log.d("users----", it.username) }

            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
        input_uname.setOnItemClickListener{parent,view,i,id->
//            val pwd=
            input_pwd.setText(users[i].password)
        }
    }

//    override fun onResume() {
//        super.onResume()
//        flag+=1
//        if (login_flag && flag>2) startActivity(Intent(context, MineActivity::class.java))
//    }

}